package cn.yilongquan.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.yilongquan.mapper.UserMapper;
import cn.yilongquan.service.IUserService;
import cn.yilongquan.user.domain.User;
import cn.yilongquan.user.query.UserQuery;
import cn.yilongquan.util.R;
import cn.yilongquan.util.RandomStringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.bytebuddy.utility.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public void add(User user) {
        //得到用户输入的密码
        String password = user.getPassword();

        //设置盐值
        String s1 = RandomStringUtils.generateSalt(10);

        //存储盐值
        user.setSalt(s1);

        //存储加密加盐值之后的密文
        user.setPassword(SecureUtil.md5(password + s1));

        userMapper.add(user);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        userMapper.batchDelete(ids);
    }

    @Override
    public R pageList(UserQuery userQuery) {
        //自动分页
        PageHelper.startPage(userQuery.getPage(), userQuery.getSize());
        List<User> users = userMapper.pageList(userQuery);
        return R.ok(new PageInfo<User>(users));
    }
}